<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Moonshot API 测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .success { background-color: #d4edda; border-color: #c3e6cb; }
        .error { background-color: #f8d7da; border-color: #f5c6cb; }
        .info { background-color: #d1ecf1; border-color: #bee5eb; }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #0056b3; }
        button:disabled { background: #6c757d; cursor: not-allowed; }
        .log {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 Moonshot API 连接测试</h1>
        
        <div class="test-section info">
            <h3>📋 测试步骤</h3>
            <ol>
                <li>确保API密钥正确</li>
                <li>检查网络连接</li>
                <li>点击测试按钮</li>
                <li>查看详细日志</li>
            </ol>
        </div>

        <div class="test-section">
            <h3>🔑 API 配置</h3>
            <input type="text" id="apiKey" placeholder="输入您的 Moonshot API 密钥" 
                   value="sk-8dydRQjgnKiM1Wg0xH6lxTgA8agLLEnQaHw2FnBY1WnbMAjk">
            <br>
            <button onclick="testApiKey()">测试 API 密钥</button>
            <button onclick="testSimpleRequest()">简单请求测试</button>
            <button onclick="testChatRequest()">聊天请求测试</button>
        </div>

        <div class="test-section">
            <h3>📊 测试结果</h3>
            <div id="status" class="info">等待测试...</div>
            <div id="log" class="log">点击上方按钮开始测试...</div>
        </div>
    </div>

    <script>
        let logElement = document.getElementById('log');
        let statusElement = document.getElementById('status');

        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logMessage = `[${timestamp}] ${message}\n`;
            logElement.textContent += logMessage;
            logElement.scrollTop = logElement.scrollHeight;
            console.log(message);
        }

        function updateStatus(message, type = 'info') {
            statusElement.textContent = message;
            statusElement.className = type;
        }

        async function testApiKey() {
            const apiKey = document.getElementById('apiKey').value.trim();
            if (!apiKey) {
                updateStatus('❌ 请输入API密钥', 'error');
                return;
            }

            log('🔑 开始测试API密钥...');
            updateStatus('🔄 测试中...', 'info');

            try {
                // 测试API密钥格式
                if (!apiKey.startsWith('sk-')) {
                    throw new Error('API密钥格式不正确，应该以 sk- 开头');
                }

                log(`✅ API密钥格式正确: ${apiKey.substring(0, 10)}...`);
                
                // 测试基本连接
                const response = await fetch('https://api.moonshot.cn/v1/models', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${apiKey}`,
                        'Content-Type': 'application/json'
                    }
                });

                log(`📡 响应状态: ${response.status} ${response.statusText}`);

                if (response.ok) {
                    const data = await response.json();
                    log(`✅ API连接成功！`);
                    log(`📋 可用模型: ${JSON.stringify(data, null, 2)}`);
                    updateStatus('✅ API密钥有效，连接成功！', 'success');
                } else {
                    const errorText = await response.text();
                    log(`❌ API请求失败: ${errorText}`);
                    updateStatus(`❌ API请求失败: ${response.status}`, 'error');
                }

            } catch (error) {
                log(`💥 测试失败: ${error.message}`);
                log(`🔍 错误详情: ${error.stack}`);
                updateStatus(`❌ 测试失败: ${error.message}`, 'error');
            }
        }

        async function testSimpleRequest() {
            const apiKey = document.getElementById('apiKey').value.trim();
            if (!apiKey) {
                updateStatus('❌ 请输入API密钥', 'error');
                return;
            }

            log('🚀 开始简单请求测试...');
            updateStatus('🔄 发送简单请求...', 'info');

            try {
                const response = await fetch('https://api.moonshot.cn/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: "kimi-k2-0905-preview",
                        messages: [
                            {
                                role: "user",
                                content: "你好，请简单回复一下"
                            }
                        ],
                        max_tokens: 100
                    })
                });

                log(`📡 响应状态: ${response.status} ${response.statusText}`);

                if (response.ok) {
                    const data = await response.json();
                    log(`✅ 简单请求成功！`);
                    log(`🤖 AI回复: ${data.choices[0].message.content}`);
                    updateStatus('✅ 简单请求成功！', 'success');
                } else if (response.status === 429) {
                    log(`🔄 检测到频率限制，自动重试中...`);
                    updateStatus(`🔄 频率限制，正在重试...`, 'info');
                    // 自动重试
                    setTimeout(() => {
                        testSimpleRequest();
                    }, 2000);
                    return;
                } else {
                    const errorText = await response.text();
                    log(`❌ 简单请求失败: ${errorText}`);
                    updateStatus(`❌ 简单请求失败: ${response.status}`, 'error');
                }

            } catch (error) {
                log(`💥 简单请求失败: ${error.message}`);
                log(`🔍 错误详情: ${error.stack}`);
                updateStatus(`❌ 简单请求失败: ${error.message}`, 'error');
            }
        }

        async function testChatRequest() {
            const apiKey = document.getElementById('apiKey').value.trim();
            if (!apiKey) {
                updateStatus('❌ 请输入API密钥', 'error');
                return;
            }

            log('💬 开始聊天请求测试...');
            updateStatus('🔄 发送聊天请求...', 'info');

            try {
                const response = await fetch('https://api.moonshot.cn/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: "kimi-k2-0905-preview",
                        messages: [
                            {
                                role: "system",
                                content: "你是 Kimi, 由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的信息。"
                            },
                            {
                                role: "user",
                                content: "请介绍一下你自己"
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 500
                    })
                });

                log(`📡 响应状态: ${response.status} ${response.statusText}`);

                if (response.ok) {
                    const data = await response.json();
                    log(`✅ 聊天请求成功！`);
                    log(`🤖 AI回复: ${data.choices[0].message.content}`);
                    updateStatus('✅ 聊天请求成功！', 'success');
                } else if (response.status === 429) {
                    log(`🔄 检测到频率限制，自动重试中...`);
                    updateStatus(`🔄 频率限制，正在重试...`, 'info');
                    // 自动重试
                    setTimeout(() => {
                        testChatRequest();
                    }, 2000);
                    return;
                } else {
                    const errorText = await response.text();
                    log(`❌ 聊天请求失败: ${errorText}`);
                    updateStatus(`❌ 聊天请求失败: ${response.status}`, 'error');
                }

            } catch (error) {
                log(`💥 聊天请求失败: ${error.message}`);
                log(`🔍 错误详情: ${error.stack}`);
                updateStatus(`❌ 聊天请求失败: ${error.message}`, 'error');
            }
        }

        // 页面加载时自动测试
        window.onload = function() {
            log('🌐 页面加载完成，准备测试...');
        };
    </script>
</body>
</html>
